package com.jinxin.platform.cdfaceacs.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.jinxin.platform.cdfaceacs.common.CommonCodeEntity;
import com.jinxin.platform.cdfaceacs.common.ResultEntity;
import com.jinxin.platform.cdfaceacs.pojo.domains.CommunityInfo;
import com.jinxin.platform.cdfaceacs.pojo.domains.JurenAcsCommunityInfo;
import com.jinxin.platform.cdfaceacs.pojo.entity.Constant;
import com.jinxin.platform.cdfaceacs.pojo.vo.CommunityDataResult;
import com.jinxin.platform.cdfaceacs.pojo.vo.ResultVO;
import com.jinxin.platform.cdfaceacs.service.JurenAcsCommunityService;
import com.jinxin.platform.cdfaceacs.service.RestTemplateService;
import com.jinxin.platform.cdfaceacs.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

import static com.alibaba.fastjson.JSON.toJSONString;

/**
 * All rights Reserved, Designed By www.beonelot.com
 *
 * @version: V1.0
 * @Copyright: www.beonelot.com Inc. All rights reserved.
 * @Description：
 * @Date: 2020-07-17
 * @Author: Lingnan
 **/
@Slf4j
@RestController
@RequestMapping("/acsCommunity")
public class AcsCommunityController {

    @Autowired
    private JurenAcsCommunityService acsCommunityService;
    @Autowired
    private RestTemplateService restTemplateService;

    @RequestMapping("/list")
    public Map<String,Object> list(@RequestParam int page, @RequestParam int limit, String name){
        HashMap param = new HashMap();
        param.put("page", page);
        param.put("limit", limit);
        param.put("name", name);
        PageInfo<JurenAcsCommunityInfo> pageInfo = acsCommunityService.listPage(page,limit,param);
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("code",0);
        resultMap.put("msg","");
        resultMap.put("count",pageInfo.getTotal());
        resultMap.put("data",pageInfo.getList());
        return resultMap;
    }

    @RequestMapping("listCommunities")
    public ResultEntity listCommunities(){
        return new ResultEntity(CommonCodeEntity.SUC_CODE,"suc",acsCommunityService.listCommunities());
    }

    @RequestMapping("/delete")
    public ResultEntity delete(String id) {
        if(StringUtils.isEmpty(id)){
            return new ResultEntity(CommonCodeEntity.PARAM_ERR,"参数异常，无法删除","");
        }
        JurenAcsCommunityInfo communityInfo = new JurenAcsCommunityInfo();
        communityInfo.setCompanyId(id);
        ResultVO resultVO = restTemplateService.housingEstateOperate(Constant.OPERATION_SIGN_DEL, communityInfo);
        if(resultVO != null && resultVO.getRstId().equals(Constant.ETO_TOKEN_RSTID_SUCCESS)){
            int count = acsCommunityService.deleteByKey(id);
            if(count > 0){
                return new ResultEntity(CommonCodeEntity.SUC_CODE,"suc","" );
            }
        }
        String desc = resultVO != null ? resultVO.getRstDesc() : "删除失败，请重试";
        return new ResultEntity(CommonCodeEntity.FAIL,desc,"");
    }
    @PostMapping("/saveOrUpdate")
    public ResultEntity addBlockInfo(JurenAcsCommunityInfo communityInfo){
        if(communityInfo == null){
            return new ResultEntity(CommonCodeEntity.PARAM_ERR,"参数异常，无法保存","");
        }
        String id = communityInfo.getCompanyId();
        int num = 0;
        ResultVO resultVO;
        if(!StringUtils.isEmpty(id)){
            try {
                resultVO = restTemplateService.housingEstateOperate(Constant.OPERATION_SIGN_EDIT, communityInfo);
            }catch (Exception e){
                e.printStackTrace();
                return new ResultEntity(CommonCodeEntity.FAIL, "编辑失败","" );
            }
            if(resultVO != null && resultVO.getRstId().equals(Constant.ETO_TOKEN_RSTID_SUCCESS)){
                communityInfo.setUpdateTime(DateUtil.dateToString(new Date(),"yyyy-MM-dd HH:mm:ss"));
                num = acsCommunityService.updateByKey(communityInfo);
            }else {
                return new ResultEntity(CommonCodeEntity.FAIL, resultVO.getRstDesc(),"" );
            }
        }else {
//            communityInfo.setAreaId(Constant.AREA_ID_SHANDONG_QINGDAO_HUANGDAO);
            try {
                resultVO = restTemplateService.housingEstateOperate(Constant.OPERATION_SIGN_ADD, communityInfo);
            }catch (Exception e){
                e.printStackTrace();
                return new ResultEntity(CommonCodeEntity.FAIL, "新增失败","" );
            }
            if(resultVO != null && resultVO.getRstId().equals(Constant.ETO_TOKEN_RSTID_SUCCESS)){
                JSONObject jsonObj = resultVO.getObject();
                if(jsonObj != null){
                    Integer companyId = jsonObj.getInteger("companyId");
                    Integer housingEstateId = jsonObj.getInteger("housingEstateId");
                    communityInfo.setCompanyId(companyId+"");
                    communityInfo.setCode(housingEstateId+"");
//                    communityInfo.setAreaName(Constant.AREA_NAME_SHANDONG_QINGDAO_HUANGDAO);
                    num = acsCommunityService.insert(communityInfo);
                }
            }else {
                return new ResultEntity(CommonCodeEntity.FAIL, resultVO.getRstDesc(),"" );
            }
        }
        if(num > 0){
            return new ResultEntity(CommonCodeEntity.SUC_CODE,"添加或更新成功","");
        }else {
            return new ResultEntity(CommonCodeEntity.FAIL, "添加或更新小区失败，请稍后重试","" );
        }

    }

    @RequestMapping("/syncData")
    public ResultEntity syncData(){
        int count = 0;
        try {
            // 1：社区服务
            ResultEntity resultEntity = restTemplateService.getCommunities(1);
            if(resultEntity != null && resultEntity.getResultCode().equals("000")){
                CommunityDataResult dataResult = (CommunityDataResult)resultEntity.getResultContent();
                List<JSONObject> jsonList = JSON.parseArray(dataResult.getObject().toString(),JSONObject.class);
                List<JurenAcsCommunityInfo> list = acsCommunityService.list(new HashMap());
                List<String> idList = new ArrayList<>();
                for(JurenAcsCommunityInfo communityInfo : list){
                    idList.add(communityInfo.getCompanyId());
                }
                for (JSONObject json : jsonList) {
                    CommunityInfo communityInfo = JSON.parseObject(toJSONString(json), CommunityInfo.class);
                    if(communityInfo != null){
                        String companyId = communityInfo.getNameId()+"";
                        JurenAcsCommunityInfo info = acsCommunityService.selectByKey(companyId);
                        if(info == null){
                            info = new JurenAcsCommunityInfo();
                            info.setCompanyId(companyId);
                            info.setName(communityInfo.getName());
                            acsCommunityService.insert(info);
                            count++;
                        }else {
                            info.setCompanyId(companyId);
                            info.setName(communityInfo.getName());
                            acsCommunityService.updateByKey(info);
                            idList.remove(companyId);
                        }
                    }
                }
                // 删除不存在数据
                for (String id : idList) {
                    acsCommunityService.deleteByKey(id);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            return new ResultEntity(CommonCodeEntity.FAIL,"同步失败,请重试","" );
        }
        log.info("成功同步小区数据"+count+"条");
        return new ResultEntity(CommonCodeEntity.SUC_CODE,"成功同步小区数据"+count+"条","");
    }

    @RequestMapping("/getAreaTree")
    public ResultEntity getAreaTree(){
        return restTemplateService.getAreaTree();
    }

}
